"""

软件测试 作业1

"""
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.firefox.webelement import FirefoxWebElement


def get(url: str) -> WebDriver:
    '''
    用url打开浏览器
    '''
    global browser
    # 注册驱动
    browser = webdriver.Firefox()
    # 打开浏览器
    browser.get(url)
    # 查找等待
    browser.implicitly_wait(1)
    return browser


def by(xpath: str) -> FirefoxWebElement:
    '''
    使用xpath获取元素
    '''
    return browser.find_element(By.XPATH, xpath)


def result() -> str:
    '''
    获取输入样例的返回值
    '''
    ret = ''
    try:
        ret = by(
            '/html/body/div[5]/div[2]/div/div[1]/ul[1]/li[1]/div/div/p').text
    except:
        ret = ''
    return '合法输入' if ret == '' else '非法输入'


def test(target: FirefoxWebElement,
         test_case: dict) -> dict:
    '''
    使用test_case对targer做测试
    '''
    map = {}
    for i, _ in test_case.items():
        target.click()
        target.clear()
        target.send_keys(i)
        email_icon.click()
        map[i] = result()
    return map


def check(result: dict, test_case: dict) -> None:
    '''
    对比测试结果和预期，输出差异
    '''
    for i, j in test_case.items():
        if result[i] != j:
            print(f"'{i}' 预期 '{j}' 结果 '{result[i]}'")


# 测试url
url = 'https://cloud.tencent.com/register'

# 测试用例及预期
test_case = {"1t!#$%&'*+-/@t.qw": "合法输入",
             "_2=?^_`{|}~@a.qw.t": "合法输入",
             "": "非法输入",
             "@qq.com": "非法输入",
             "tang@": "非法输入",
             "tangqq.com": "非法输入",
             "∫∮@qq.com": "非法输入",
             "\w@qq.com": "非法输入",
             ".q@qq.com": "非法输入",
             "@12@qq.com": "非法输入",
             "quanwei@tang": "非法输入"}


if __name__ == '__main__':
    # 用浏览器访问url
    url = 'https://cloud.tencent.com/register'
    get(url)

    # 转到邮箱注册
    xpath = '/html/body/div[3]/div[1]/div[2]/div/div[1]'
    by(xpath).click()
    xpath = '/html/body/div[3]/div[1]/div[2]/div/div[2]/a[2]/i'
    by(xpath).click()

    # 获取输入框
    xpath = '/html/body/div[5]/div[2]/div/div[1]/ul[1]/li[1]/div/div/input'
    input = by(xpath)

    # 获取一个图标：目的是取消输入框聚焦
    xpath = '/html/body/div[5]/div[1]/div[2]/div/i'
    email_icon = by(xpath)

    # 执行测试
    result = test(input, test_case)

    # check
    check(result, test_case)

    # 关闭浏览器
    browser.close()

class C:
    # xpath constant
    INPUT_BOX='...'
    SUBMIB_BTN='...'
    EMAIL_ICON='...'
    

input_box=by(C.INPUT_BOX)